// Author: Bjorn Schobben


#include <assert.h>
#include "TextureManager.h"

// The default texture to use when there is a missing texture
const char *TextureManager::MISSINGTEXTURE = "textures/missing.png";

TextureManager::TextureManager(): emptyTexture(Pixel(255,255,255))
{
	try
	{
		emptyTexture = Texture(MISSINGTEXTURE);
	} 
	catch(std::runtime_error e)
	{
		// couldn't load empty texture, use solid color then
	}

	// Make sure the empty texture has a transparent user color
	emptyTexture.SetUserColor( Pixel() );
}

TextureManager::TextureManager(const TextureManager& rhs): emptyTexture(rhs.emptyTexture)
{
	std::vector<Texture*>::const_iterator it;

	for(it = rhs.textures.begin(); it != rhs.textures.end(); ++it)
	{
		const Texture *tex = *it;

		// Add a new copy
		textures.push_back(new Texture(*tex));
	}
}

TextureManager::~TextureManager()
{
	Clear();
}

void TextureManager::Clear()
{
	std::vector<Texture*>::iterator it;

	// Delete each texture
	for(it = textures.begin(); it != textures.end(); ++it)
	{
		Texture *tex = *it;

		delete tex;
	}

	// Clear the list
	textures.clear();
}

bool TextureManager::ValidIndex(unsigned int tindex)
{
	if (tindex == -1 || tindex < GetTextureCount())
	{
		return true;
	}
	else
	{
		return false;
	}
}

// Get amount of textures in the list
unsigned int TextureManager::GetTextureCount() const
{
	return textures.size();
}

void TextureManager::ChangeUserColor(unsigned int tindex, const Pixel& userColor)
{
	assert(tindex < GetTextureCount());

	std::vector<Texture*>::iterator it = textures.begin()+tindex;
	Texture *texture = *it;

	texture->SetUserColor(userColor);
}

// Add new texture to the list and return its index
unsigned int TextureManager::AddTexture(const Texture& texture)
{
	unsigned int index = GetTextureCount();

	textures.push_back(new Texture(texture));

	return index;
}

// Remove texture from the list
void TextureManager::RemoveTexture(unsigned int index)
{
	assert(index < GetTextureCount());

	std::vector<Texture*>::iterator it = textures.begin()+index;
	Texture *texture = *it;

	textures.erase(it);
	delete texture;
}

// Get texture from index
const Texture& TextureManager::GetTexture(unsigned int tindex) const
{
	// "empty" index
	if (-1 == tindex)
		return emptyTexture;
	else
		return *textures[tindex];
}

// Get the empty texture
const Texture& TextureManager::GetEmptyTexture() const
{
	return emptyTexture;
}
